package microcredit.gui;

import java.awt.BorderLayout;

import javax.swing.JPanel;

import microcredit.gui.handler.GroupHandler;
import microcredit.gui.handler.MemberHandler;
import microcredit.gui.handler.ReportHandler;
import microcredit.gui.handler.TrainingHandler;
import microcredit.gui.selector.SelectorPanel;
import microcredit.model.Member;
import microcredit.model.MemberGroup;
import microcredit.model.Report;
import microcredit.model.TrainingType;

public class MainFrameController {

	private SelectorPanel<?> currentSelector;
	private MainFrame mainFrame;
	
	public MainFrameController() {
	}
	
	public void refreshCurrentSelector() {
		if (currentSelector != null) {
			currentSelector.refresh();
		}
	}
	
	public void setMainFrame(MainFrame mainFrame) {
		this.mainFrame = mainFrame;
	}
	
	public void selectMemberShip() {
		MemberHandler handler = new MemberHandler(mainFrame);
		SelectorPanel<Member> panel = new SelectorPanel<Member>(Member.class, 
				handler, handler, handler, handler, null, null, handler, null);
		select(panel, "Member");
	}
	
	public void selectGroups() {
		GroupHandler handler = new GroupHandler();
		SelectorPanel<MemberGroup> panel = new SelectorPanel<MemberGroup>(MemberGroup.class, 
				handler, handler, handler, handler, null, null, handler, null);
		select(panel, "Group");
	}
	
	public void selectTrainings() {
		TrainingHandler handler = new TrainingHandler(mainFrame);
		SelectorPanel<TrainingType> panel = new SelectorPanel<TrainingType>(TrainingType.class, 
				handler, handler, handler, handler, null, null, handler, null);
		select(panel, "Training type");
	}
	
	public void selectReports() {
		ReportHandler handler = new ReportHandler();
		SelectorPanel<Report> panel = new SelectorPanel<Report>(Report.class, 
				handler, handler, null, null, null, null, null, null);
		select(panel, "Report");
	}
	
	private <E> void select(SelectorPanel<E> panel, String title) {
		JPanel viewPanel = mainFrame.getViewPanel();
		viewPanel.removeAll();
		viewPanel.add(panel, BorderLayout.CENTER);
		panel.focusDefaultComponent();
		currentSelector = panel;
		mainFrame.addTitleSuffix(title);
		((JPanel)mainFrame.getContentPane()).revalidate();
		((JPanel)mainFrame.getContentPane()).repaint();
	}
}
